package com.demo.cms.action.manage;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.demo.core.context.RefreshModel;
import com.demo.core.context.event.RefreshEvent;
import com.demo.core.model.Member;
import com.demo.core.model.Role;
import com.demo.core.model.RoleFunction;
import com.demo.core.model.Site;
import com.demo.core.model.SiteFunction;
import com.demo.core.service.base.RoleFunctionService;
import com.demo.core.service.base.RoleService;
import com.demo.core.service.base.SiteFunctionService;
import com.demo.core.service.exception.RoleAlreadyExistedException;
import com.demo.core.util.collection.JsonUtils;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;
import com.demo.webapp.context.MultisiteContextHolder;

/**
 * 角色管理Action
 * @author ryuu.kk
 */
@Function(id = 100800, pid = 10, code = "manage.role")
public class RoleAction extends PageAction implements ApplicationContextAware  {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -1394426645332067661L;

	/**
	 * 角色ID
	 */
	private Long id;
	
	/**
	 * 功能ID
	 */
	private Long functionId;
	
	/**
	 * 站点功能模型(树结构)
	 */
	private SiteFunction tree;
	
	/**
	 * 树的json字符串
	 */
	private String json;
	
	/**
	 * 角色模型
	 */
	private Role role;
	
	/**
	 * 角色列表
	 */
	private List<Role> roleList;
	
	/**
	 * 会员列表
	 */
	private List<Member> memberList;
	
	/**
	 * 角色功能模型列表
	 */
	private List<RoleFunction> roleFunctionList;
	
	/**
	 * 角色服务
	 */
	private RoleService roleService;
	
	/**
	 * 角色功能模型服务
	 */
	private RoleFunctionService roleFunctionService;

	/**
	 * Spring容器上下文
	 */
	private ApplicationContext applicationContext;
	
	/**
	 * 站点功能模型服务
	 */
	private SiteFunctionService siteFunctionService;

	@Function(id = 100801, pid = 100800, code = "manage.role.execute")
	public String execute() {
		
		return SUCCESS;
	}
	
	/**
	 * 角色一览
	 * @return String
	 */
	@Function(id = 100810, pid = 100800, code = "manage.role.list")
	public String list() {
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		this.roleList = roleService.findList(siteId);
		//memberRoleService.findRole(roleId);
		//addActionMessage("生成角色列表");
		// 获得功能树
		//tree();
		
		return SUCCESS;
	}
	
	/**
	 * 角色创建页面
	 * @return String
	 */
	@Function(id = 100820, pid = 100800, code = "manage.role.create")
	public String create() {
		
		return SUCCESS;
	}
	
	/**
	 * 角色创建保存
	 * @return String
	 */
	@Function(id = 100830, pid = 100800, code = "manage.role.save")
	public String save() {
		
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		role.setSiteId(siteId);
		// 自定义角色
		role.setType(Role.ROLE_TYPE_CUSTOM);
		// 可以更新维护和删除
		role.setStatus(Role.ROLE_STATUS_RWD);
		
		try {
			roleService.save(role);
		} catch (RoleAlreadyExistedException e) {
			addActionError(getText(e.getI18n(), "", role.getName()));
			return INPUT;
		}
		addActionMessage(getText("role.added", "", role.getName()));
		return CALLBACK;
	}
	
	/**
	 * 角色编辑
	 * @return String
	 */
	@Function(id = 100840, pid = 100800, code = "manage.role.edit")
	public String edit() {
		
		role = roleService.find(id);
		if (role.getStatus().lastIndexOf(Role.ROLE_STATUS_W) == -1) {
			// 数据不能由系统修改
			addActionError(getText("role.cannot.modify", "角色{0} 不能修改.", role.getName()));
			// 取消操作
			return CANCEL;
		}
		return SUCCESS;
	}
	
	/**
	 * 用户更新画面
	 * @return String
	 */
	@Function(id = 100850, pid = 100800, code = "manage.role.update")
	public String update() {
		
		Role roleTmp = roleService.find(id);
		if (roleTmp.getStatus().lastIndexOf(Role.ROLE_STATUS_W) == -1) {
			// 数据不能由系统修改
			addActionError(getText("role.cannot.modify", "角色{0} 不能修改.", roleTmp.getName()));
			return INPUT;
		}
		// 更新用户信息
		roleService.update(id, role.getName(), role.getTitle(), role.getDescription());
		// 更新有效期限日和可用标志
		roleService.valid(id, role.getExpireDay(), role.isEnabled());
		addActionMessage(getText("role.updated", "角色{0} 修改成功.", roleTmp.getName()));
		return CALLBACK;
	}
	
	/**
	 * 角色删除画面
	 * @return String
	 */
	@Function(id = 100860, pid = 100800, code = "manage.role.delete")
	public String delete() {
		
		Role roleTmp = roleService.find(id);
		if (roleTmp.getStatus().lastIndexOf(Role.ROLE_STATUS_W) == -1) {
			// 数据不能由系统修改
			addActionError(getText("role.cannot.delete", "角色{0} 不能删除.", roleTmp.getName()));
			return CALLBACK;
		}
		// 需要先判断role的type
		roleService.delete(id);
		addActionError(getText("role.deleted", "角色{0} 已删除.", roleTmp.getName()));
		return CALLBACK;
	}
	
	/**
	 * 功能树
	 * @return String
	 */
	@Function(id = 100870, pid = 100800, code = "manage.role.tree")
	public String tree() {
		// 取得角色ID
		Site site = MultisiteContextHolder.getSite();
		// 角色组ID
		Long siteId = site.getId();
		// 角色最大功能集合(Tree)
		if (functionId == null) {
			//functionId = Constants.FUNCTION_ROOT_ID;
			this.tree = siteFunctionService.querySiteFunctionTreeRoot(siteId);
		} else {
			// 取得站点功能树
			this.tree = siteFunctionService.querySiteFunctionTree(functionId, siteId);
		}
		
		// 取得角色功能树
		Map<Long, RoleFunction> rfMap = roleFunctionService.queryMap(siteId, id, true);
		Set<Long> keySet = rfMap.keySet();
		// 生成json树
		json = JsonUtils.zTree(tree, true, keySet.toArray());
		return SUCCESS;
	}
	
	/**
	 * 创建角色功能信息
	 * @return String
	 */
	@Function(id = 100880, pid = 100800, code = "manage.role.enabled")
	public String enable() {
		
		Site site = getSite();
		Long siteId = site.getId();
		
		// 取得角色ID
		if (roleFunctionList != null) {
			roleFunctionService.deleteAll(id, siteId);
			roleFunctionService.saveList(id, roleFunctionList);
//			for (RoleFunction sf : roleFunctionList) {
//				//roleFunctionService.(sf.getId(), "RWD", sf.isEnabled());
//				sf.setCreateDate(new Date());
//				sf.setStatus("RWD");
//				sf.setRoleId(id);
//				// 为生成tree结果,将function的主键ID作为SF的主键ID了
//				sf.setFunctionId(sf.getId());
//				roleFunctionService.save(sf);
//			}
			addActionMessage("角色授权更新成功.");
			
			// 定义刷新事件模型
			RefreshModel model = new RefreshModel();
			model.setType(RefreshModel.MODEL_TYPE_METHOD);
			model.setSiteId(siteId);
			// 定义刷新事件
			RefreshEvent event = new RefreshEvent(model) {
				/**
				 * 版本序列化ID
				 */
				private static final long serialVersionUID = -1928151224804257473L;
			};
			
			applicationContext.publishEvent(event);
		}
		return NONE;
	}
	
	/**
	 * 角色功能信息展示
	 * @return String
	 */
	@Function(id = 100890, pid = 100800, code = "manage.role.view")
	public String view() {
		// 取得角色ID
		Site site = MultisiteContextHolder.getSite();
		// 角色组ID
		Long siteId = site.getId();
		roleFunctionList = roleFunctionService.query(siteId, id);
		return SUCCESS;
	}
	
	/**
	 * 角色功能授权
	 * @return String
	 */
	public String auth() {
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		this.roleList = roleService.findList(siteId);
		//memberRoleService.findRole(roleId);
		//addActionMessage("生成角色列表");
		// 获得功能树
		tree();
		
		return SUCCESS;
	}
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public List<Member> getMemberList() {
		return memberList;
	}

	public Long getFunctionId() {
		return functionId;
	}

	public void setFunction(Long functionId) {
		this.functionId = functionId;
	}

	public SiteFunction getTree() {
		return tree;
	}

	public String getJson() {
		return json;
	}

	public List<RoleFunction> getRoleFunctionList() {
		return roleFunctionList;
	}

	public void setRoleFunctionList(List<RoleFunction> roleFunctionList) {
		this.roleFunctionList = roleFunctionList;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public void setRoleFunctionService(RoleFunctionService roleFunctionService) {
		this.roleFunctionService = roleFunctionService;
	}

	public void setSiteFunctionService(SiteFunctionService siteFunctionService) {
		this.siteFunctionService = siteFunctionService;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

}
